package com.fred.taobao.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.fred.taobao.domain.MonthSellDomain;
import com.fred.taobao.util.SqlUtil;

public class MonthSellDao {
	public List<MonthSellDomain> getMonthsSell(String startDate,String endDate){
		SqlUtil sqlUtil=new SqlUtil();
		Connection conn=sqlUtil.getConnection();
		PreparedStatement pre=null;
		ResultSet result=null;
		Calendar calStart = Calendar.getInstance();
		Calendar calEnd=Calendar.getInstance();
		SimpleDateFormat sdf=new SimpleDateFormat();
		sdf.applyPattern("yyyy-MM-dd");
		Date dateStartDate=null;
		Date dateEndDate=null;
		try{
			dateStartDate=sdf.parse(startDate);
			dateEndDate=sdf.parse(endDate);
		}catch(Exception e){
			e.printStackTrace();
		}
		calEnd.setTime(dateEndDate);
		calEnd.add(Calendar.MONTH, 1);
		calEnd.set(Calendar.DAY_OF_MONTH,1);
		
		calStart.setTime(dateStartDate);
		calStart.set(Calendar.DAY_OF_MONTH,1);
		sdf.applyPattern("yyyy-MM-dd HH:mm:ss");
		try{
			List<MonthSellDomain> monthsSell=new ArrayList<MonthSellDomain>();
			while(calStart.before(calEnd)){
				List<String> nicks=new ArrayList<String>();
				MonthSellDomain monthSellDomain=new MonthSellDomain();
				monthSellDomain.setDate((sdf.format(calStart.getTime())).substring(0, 7));
				int orderNum=0;
				float orderTotalFee=0;
				int itemTotalNum=0;
				pre=conn.prepareStatement("select * from sell_table where order_date>=? and order_date<=? ");
				pre.setString(1,sdf.format(calStart.getTime()));
				calStart.add(Calendar.MONTH, 1);
				pre.setString(2, sdf.format(calStart.getTime()));
				result=pre.executeQuery();
				while(result.next()){
					itemTotalNum+=result.getInt("order_number");
					orderNum=result.getRow();
					orderTotalFee+=result.getFloat("total_fee");
					nicks.add(result.getString("buyer_nick"));
				}
				
				monthSellDomain.setBuyerNum(nicks.size());
				monthSellDomain.setOrderItemNum(itemTotalNum);
				monthSellDomain.setOrderNum(orderNum);
				monthSellDomain.setOrderTotalFee(orderTotalFee);
				monthsSell.add(monthSellDomain);
			}
			return monthsSell;
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}finally{
			try{
				if(result!=null){
					result.close();
				}
				if(pre!=null){
					pre.close();
				}
				if(conn!=null){
					conn.close();
				}
			}catch(Exception e){
				e.printStackTrace();
			}
		}
	}
}
